<template>
  <el-dialog
    :title="$t('msg.excel.title')"
    :model-value="modelValue"
    @close="closed"
    width="30%"
  >
    <el-input v-model="excelName" :placeholder="$t('msg.excel.placeholder')" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.excel.close') }}</el-button>
        <el-button type="primary" @click="onConfirm" :loading="loading">{{
          $t('msg.excel.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { watchSwitchLang } from '@/utils/i18n';
import { getUserManageAllList } from '@/api/user-manage';
import { USER_RELATIONS, formatJson } from './Export2ExcelConstants';

defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
});

const emits = defineEmits(['update:modelValue']);

const i18n = useI18n();
let exportDefaultName = i18n.t('msg.excel.defaultName');
const excelName = ref('');
excelName.value = exportDefaultName;

watchSwitchLang(() => {
  exportDefaultName = i18n.t('msg.excel.defaultName');
  excelName.value = exportDefaultName;
});

const loading = ref(false);
const onConfirm = async () => {
  loading.value = true;
  const allUser = (await getUserManageAllList()).list;

  const data = formatJson(USER_RELATIONS, allUser);

  // 导入工具包
  const excel = await import('@/utils/Export2Excel');

  excel.export_json_to_excel({
    // excel 表头
    header: Object.keys(USER_RELATIONS),
    // excel 数据（二维数组结构）
    data,
    // 文件名称
    filename: excelName.value || exportDefaultName,
    // 是否自动列宽
    autoWidth: true,
    // 文件类型
    bookType: 'xlsx'
  });

  closed();
};

const closed = () => {
  emits('update:modelValue', false);
};
</script>

<style lang='scss' scoped></style>
